package com.bajiao.common.util.vans;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

@Slf4j
public class VansTool {

    /**
     * @Description
     * 手机号加密
     * @date 2024/12/5 16:32
     * @author FanJq
     * @param mobile
     * @return {@link String}
     */
    public static String encryptMobile(String mobile) {
        String str = "****";
        StringBuilder sb = new StringBuilder(mobile);
        StringBuilder replace = sb.replace(3, 7, str);
        return replace.toString();
    }

    /**
     * @Description
     * 小程序解密用户数据
     * @date 2024/12/11 17:30
     * @author FanJq
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return {@link JSONObject}
    */
    public static JSONObject decryptionUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description
     * 判断密码的用户安全等级
     * @date 2024/12/12 9:24
     * @author FanJq
     * @param password
     * @return {@link int}
    */
    public int passwordSecurityLevel(String password) {
        if (password.length() < 6) {
            return 0;
        } else {
            if (password.matches("^\\d+$")) {
                return 1;
            } else if (password.matches("^[a-zA-Z]+$")) {
                return 1;
            } else if (password.matches(
                    "(?i)^((\\d+[\\da-z]*[a-z]+)|([a-z]+[\\da-z]*\\d+)|([a-z]+[\\da-z]*[a-z]*)|(\\d+[\\da-z]*\\d*))$")) {
                return 2;
            }
        }
        return 0;
    }

    /**
     * @Description
     * 根据阿里云图片路径生成byte字节数组
     * @date 2025/1/3 17:24
     * @author FanJq
     * @param img
     * @return {@link byte[]}
    */
    public static byte[] imgPathBytes(String img) {
        // 设置参数
        InputStream in = null;
        ByteArrayOutputStream byteArrOps = null;
        int length;
        byte[] buffer = new byte[1024 * 5];
        byte[] data = null;
        try {
            URL url = new URL(img);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(1000 * 60);
            if (urlConnection.getResponseCode() == 200) {
                in = urlConnection.getInputStream();
                byteArrOps = new ByteArrayOutputStream();
                while ((length = in.read(buffer)) != -1) {
                    byteArrOps.write(buffer, 0, length);
                }
                byteArrOps.flush();
                data = byteArrOps.toByteArray();
            }
        } catch (Exception e) {
            log.error("图片上传出现异常: {}, url为： {}", e, img);
            return null;
        } finally {
            try {
                if (byteArrOps != null) {
                    byteArrOps.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error("关闭异常", e);
            }
        }
        return data;
    }
}
